﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using EntityManage;

public partial class Modules_Personal_TargetAssignApproval : System.Web.UI.Page
{
    IPerf_Personal_TargetOwnerHandler toHandler = new Perf_Personal_TargetOwnerManage();
    ISys_UserHandler userHandler = new Sys_UserManage();
    ISys_OrganizationHandler orgHandler = new Sys_OrganizationManage();
    ISys_PostHandler postHandler = new Sys_PostManage();
    IPerf_Personal_FirstAssignHandler firstAssignHandler = new Perf_Personal_FirstAssignManage();
    IPerf_Flow_TraceHandler flowTraceHandler = new Perf_Flow_TraceManage();
    IPerf_FlowHandler flowHandler = new Perf_FlowManage();
    IPerf_Flow_StepsHandler fstepHandler = new Perf_Flow_StepsManage();
    IPerf_Personal_ModTargetHandler modTargetHandler = new Perf_Personal_ModTargetManage();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            ViewState["OrderBy"] = "Status";
            ViewState["Accending"] = "asc";

            dataBind(string.Empty, null);
          
        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("302030"))
            {
                btnApprove.Visible = strPur.Contains("302031");
            }
            else
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    #region DataBind
    
    /// <summary>
    /// 初始化岗位信息表
    /// </summary>
    private void dataBind(string whereClause, SqlParameter[] parms)
    {
        try
        {
            FillSearchDDL();

            int counter = 0;
            DataTable dt = new DataTable();

            #region 读取与登录用户有关的流程步骤ID，根据这些ID来读取与登录用户有关的记录

            int userId = int.Parse(Session["CurrentUserID"].ToString());
            string businessIds = FlowTrace.GetUserCurrentFlowBusinessIds(userId, (int)Enums.PerfFlowIDs.PersonalFirstAssignApproval);

            whereClause = " ID in (" + businessIds + ")" + (whereClause == string.Empty ? "" : (" and " + whereClause));
            
            #endregion

            dt = modTargetHandler.GetPerf_Personal_ModTargetByPageList(whereClause, parms, ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);

            counter = modTargetHandler.GetCounter(whereClause, parms);

            this.AspNetPager.RecordCount = counter;
            gvAssignApproveList.DataSource = dt;
            gvAssignApproveList.DataBind();
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();

        if (ViewState["SearchOrgID"] != null)
        {
            whereClause += " and Org_ID = @Org_ID";
            lstParm.Add(new SqlParameter("@Org_ID", int.Parse(ViewState["SearchOrgID"].ToString())));
        }

        if (ViewState["SearchPostID"] != null)
        {
            whereClause += " and Post_ID = @Post_ID";
            lstParm.Add(new SqlParameter("@Post_ID", int.Parse(ViewState["SearchPostID"].ToString())));
        }

        if (ViewState["SearchTOID"] != null)
        {
            whereClause += " and TargetOwner_ID = @TargetOwner_ID";
            lstParm.Add(new SqlParameter("@TargetOwner_ID", int.Parse(ViewState["SearchTOID"].ToString())));
        }

        parms = lstParm.ToArray();
    }

    private void FillSearchDDL()
    {
        FillSearchOrg();
        FillSearchPost();
        FillSearchTO();
    }

    private void FillSearchOrg()
    {
        DataTable dt = orgHandler.GetSys_OrganizationList(" Status = @Status and (Type = @Type1 or Type = @Type2)", new SqlParameter[]{
            new SqlParameter("@Status",(int)Enums.OrgStatus.Valid), new SqlParameter("@Type1", (int)Enums.OrgType.ICU), new SqlParameter("@Type2", (int)Enums.OrgType.Office)}, " Name asc");
        ddlSearchOrg.DataTextField = "Name";
        ddlSearchOrg.DataValueField = "ID";
        ddlSearchOrg.DataSource = dt;
        ddlSearchOrg.DataBind();
        ddlSearchOrg.Items.Insert(0, new ListItem("全部....", "0"));
    }

    private void FillSearchPost()
    {
        DataTable dt = postHandler.GetSys_PostList(" Status = @Status", new SqlParameter[] { new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid) }, " Name asc");
        ddlSearchPost.DataTextField = "Name";
        ddlSearchPost.DataValueField = "ID";
        ddlSearchPost.DataSource = dt;
        ddlSearchPost.DataBind();
        ddlSearchPost.Items.Insert(0, new ListItem("全部....", "0"));
    }


    private void FillSearchTO()
    {
        DataTable dt = toHandler.GetPerf_Personal_TargetOwnerList();
        ddlSearchTo.DataTextField = "Name";
        ddlSearchTo.DataValueField = "ID";
        ddlSearchTo.DataSource = dt;
        ddlSearchTo.DataBind();
        ddlSearchTo.Items.Insert(0, new ListItem("全部....", "0"));
    }

    #endregion

    #region gvAssignApproveList

    protected void gvAssignApproveList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        
    }

    protected void gvAssignApproveList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HtmlInputCheckBox chkSelected = (HtmlInputCheckBox)e.Row.FindControl("chkSelected");
            if (int.Parse(e.Row.Cells[7].Text.Trim()) == (int)Enums.PersonalModTargetStatus.OnFlowing)
                chkSelected.Visible = true;
            else
                chkSelected.Visible = false;

            if (e.Row.RowIndex > -1)
            {
                // 分配人
                Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(int.Parse(e.Row.Cells[2].Text));
                if (userQuery != null)
                    e.Row.Cells[2].Text = userQuery.Name;

                // 单位
                Sys_OrganizationQuery orgQuery = orgHandler.GetSys_OrganizationQuery(int.Parse(e.Row.Cells[3].Text));
                if (orgQuery != null)
                    e.Row.Cells[3].Text = orgQuery.Name;

                // 岗位
                Sys_PostQuery postQuery = postHandler.GetSys_PostQuery(int.Parse(e.Row.Cells[4].Text));
                if (postQuery != null)
                    e.Row.Cells[4].Text = postQuery.Name;

                // 指标套
                Perf_Personal_TargetOwnerQuery toQuery = toHandler.GetPerf_Personal_TargetOwnerQuery(int.Parse(e.Row.Cells[5].Text));
                if (toQuery != null)
                    e.Row.Cells[5].Text = toQuery.Name;

                // 状态
                Enums.PersonalModTargetStatus toStatus = (Enums.PersonalModTargetStatus)int.Parse(e.Row.Cells[7].Text);
                e.Row.Cells[7].Text = Enums.GetPersonalModTargetStatus(toStatus);

                ImageButton ibtnViewFlow = (ImageButton)e.Row.FindControl("ibtnViewFlow");
                if(ibtnViewFlow != null)
                    ibtnViewFlow.Visible = (toStatus != Enums.PersonalModTargetStatus.NewAssign);
            }
        }
    }

    protected void gvAssignApproveList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        RefreshDataGridView();
    }

    #endregion

    #region Button
    
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (!ddlSearchOrg.SelectedValue.Equals("0"))
            ViewState["SearchOrgID"] = ddlSearchOrg.SelectedValue;
        else
            ViewState["SearchOrgID"] = null;

        if (!ddlSearchPost.SelectedValue.Equals("0"))
            ViewState["SearchPostID"] = ddlSearchPost.SelectedValue;
        else
            ViewState["SearchPostID"] = null;

        if (!ddlSearchTo.SelectedValue.Equals("0"))
            ViewState["SearchTOID"] = ddlSearchTo.SelectedValue;
        else
            ViewState["SearchTOID"] = null;

        RefreshDataGridView();
    }

    protected void ApproveButton_Click(object sender, EventArgs e)
    {
            RefreshDataGridView();
    }

    protected void AspNetPager_PageChanged(object src, EventArgs e)
    {
        RefreshDataGridView();
    }

    #endregion

    private void RefreshDataGridView()
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParms(ref clause, ref parms);
        dataBind(clause, parms);
    }

}
